package com.example.contextcube.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.contextcube.R;
import com.example.contextcube.db.DictionaryDatabaseHelper;
import com.example.contextcube.model.Word;
import com.example.contextcube.util.FavoriteManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 单词列表适配器
 */
public class WordAdapter extends RecyclerView.Adapter<WordAdapter.WordViewHolder> implements FavoriteManager.FavoriteChangeListener {
    private List<Word> words = new ArrayList<>();
    private OnWordClickListener listener;
    private OnFavoriteClickListener favoriteListener;
    private DictionaryDatabaseHelper dbHelper;
    private FavoriteManager favoriteManager;

    /**
     * 单词点击监听接口
     */
    public interface OnWordClickListener {
        void onWordClick(Word word);
    }
    
    /**
     * 收藏按钮点击监听接口
     */
    public interface OnFavoriteClickListener {
        void onFavoriteClick(Word word, boolean isFavorite);
    }

    public WordAdapter(OnWordClickListener listener) {
        this.listener = listener;
        this.favoriteManager = FavoriteManager.getInstance();
        this.favoriteManager.addListener(this);
    }
    
    public WordAdapter(OnWordClickListener listener, OnFavoriteClickListener favoriteListener, DictionaryDatabaseHelper dbHelper) {
        this.listener = listener;
        this.favoriteListener = favoriteListener;
        this.dbHelper = dbHelper;
        this.favoriteManager = FavoriteManager.getInstance();
        this.favoriteManager.addListener(this);
        
        // 确保FavoriteManager已设置数据库
        if (dbHelper != null) {
            favoriteManager.setDatabaseHelper(dbHelper);
            // 强制刷新收藏状态
            favoriteManager.loadAllFavorites();
        }
    }

    @NonNull
    @Override
    public WordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_word_list, parent, false);
        return new WordViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull WordViewHolder holder, int position) {
        Word word = words.get(position);
        
        // 设置单词文本
        holder.wordText.setText(word.getWord());

        
        // 设置中文释义
        holder.definitionText.setText(word.getTranslation());
        
        // 从FavoriteManager获取最新的收藏状态
        boolean isFavorited = favoriteManager.isFavorited(word.getWord());
        word.setFavorite(isFavorited);
        
        // 设置收藏状态
        updateFavoriteButton(holder, word);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onWordClick(word);
            }
        });
        
        // 设置收藏按钮点击事件
        holder.favoriteButton.setOnClickListener(v -> {
            // 切换收藏状态
            boolean newFavoriteState = !word.isFavorite();
            word.setFavorite(newFavoriteState);
            
            // 更新UI
            updateFavoriteButton(holder, word);
            
            // 通过FavoriteManager更新收藏状态
            favoriteManager.toggleFavorite(word.getWord(), newFavoriteState);
            
            // 通知回调
            if (favoriteListener != null) {
                favoriteListener.onFavoriteClick(word, newFavoriteState);
            }
        });
    }
    
    /**
     * 更新收藏按钮的状态
     */
    private void updateFavoriteButton(WordViewHolder holder, Word word) {
        // 根据收藏状态设置图标
        if (word.isFavorite()) {
            holder.favoriteButton.setImageResource(R.drawable.ic_favorite);
        } else {
            holder.favoriteButton.setImageResource(R.drawable.ic_favorite_border);
        }
    }

    @Override
    public int getItemCount() {
        // 修复空指针异常：确保words不为null
        return words != null ? words.size() : 0;
    }

    /**
     * 更新单词列表数据
     */
    public void setWords(List<Word> words) {
        // 修复空指针异常：如果传入null则使用空列表
        this.words = words != null ? words : new ArrayList<>();
        
        // 更新收藏状态
        for (Word word : this.words) {
            word.setFavorite(favoriteManager.isFavorited(word.getWord()));
        }
        
        notifyDataSetChanged();
    }
    
    /**
     * 设置收藏点击监听器
     */
    public void setOnFavoriteClickListener(OnFavoriteClickListener listener) {
        this.favoriteListener = listener;
    }
    
    /**
     * 设置数据库助手
     */
    public void setDatabaseHelper(DictionaryDatabaseHelper dbHelper) {
        this.dbHelper = dbHelper;
        
        // 确保FavoriteManager已设置数据库
        if (favoriteManager != null && dbHelper != null) {
            favoriteManager.setDatabaseHelper(dbHelper);
        }
    }
    
    /**
     * 获取指定位置的单词
     */
    public Word getWordAt(int position) {
        if (words != null && position >= 0 && position < words.size()) {
            return words.get(position);
        }
        return null;
    }
    
    /**
     * FavoriteManager回调：当收藏状态变化时更新UI
     */
    @Override
    public void onFavoriteChanged(String wordStr, boolean isFavorite) {
        // 查找列表中是否有相同的单词，并更新其状态
        for (int i = 0; i < words.size(); i++) {
            Word word = words.get(i);
            if (word.getWord().equals(wordStr)) {
                word.setFavorite(isFavorite);
                notifyItemChanged(i);
                break;
            }
        }
    }
    
    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        // 移除监听器避免内存泄漏
        favoriteManager.removeListener(this);
    }

    /**
     * ViewHolder类
     */
    static class WordViewHolder extends RecyclerView.ViewHolder {
        TextView wordText;
        TextView phoneticText;
        TextView definitionText;
        ImageButton favoriteButton;

        public WordViewHolder(@NonNull View itemView) {
            super(itemView);
            wordText = itemView.findViewById(R.id.word_text);
            phoneticText = itemView.findViewById(R.id.phonetic_text);
            definitionText = itemView.findViewById(R.id.definition_text);
            favoriteButton = itemView.findViewById(R.id.favorite_button);
        }
    }
} 